import { Logger, ValidationPipe } from '@nestjs/common'
import type { NestExpressApplication } from '@nestjs/platform-express'
import { NestFactory } from '@nestjs/core'
const limit = require('express-rate-limit')
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'
import { join } from 'path'

import { AppModule } from './app.module'
import { HttpExceptionFilter } from './common/filters/http-exception/http-exception.filter'
import { ResponseInterceptor } from './common/interceptor/response/response.interceptor'
import { XmlMiddleware } from './common/middleware/xml/xml.middleware'

async function main() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: new Logger(),
    cors: true
  })

  app.useStaticAssets(join(process.cwd(), './public'))
  app.setBaseViewsDir(join(process.cwd(), './public/views'))
  app.setViewEngine('hbs')

  // 全局注册通用验证管道
  app.useGlobalPipes(new ValidationPipe())
  // 全局注册通用异常过滤器
  app.useGlobalFilters(new HttpExceptionFilter(new Logger()))
  // 全局中间件注册
  app.use(new XmlMiddleware().use)

  app.enableCors({
    origin: '*',
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    preflightContinue: true,
    optionsSuccessStatus: 204
  })
  app.use(
    limit({
      windowMs: 15 * 60 * 1000, // 15 minutes
      max: 100 // limit each IP to 100 requests per windowMs
    })
  )

  app.useGlobalInterceptors(new ResponseInterceptor())

  const config = new DocumentBuilder()
    .addBearerAuth()
    .setTitle('nest 入门 客户端接口')
    .setDescription('使用 nest 编写常用接口')
    .setVersion('1.0.0')
    .addTag('default')
    .addServer(`http://localhost:${process.env.PORT}`)
    .build()
  const document = SwaggerModule.createDocument(app, config)
  SwaggerModule.setup('api', app, document)
  await app.listen(process.env.PORT)
  console.log('OK => ', `http://localhost:${process.env.PORT}`)
}
main()
